package at.fpmedv.eclipse.helma.core;

import helma.framework.core.Application;
import helma.framework.core.Prototype;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;

import at.fpmedv.eclipse.helma.util.ResourceContainer;

/**
 * represents an helma app in the tree view
 * 
 * @author fpm
 * 
 */
public class HelmaAppTreeObject implements ITreeParent {
	private Application app;
	

	public HelmaAppTreeObject(Application app) {
		this.app = app;
	}

	/**
	 * Always generates the children on the fly
	 */
	public ITreeObject[] getChildren() {
		
		Collection<Prototype> prototypes = app.typemgr.getPrototypes();
		HashMap<String, HelmaPrototypeTreeObject> intermediateResult = new HashMap<String, HelmaPrototypeTreeObject>();
		// generate the prototypes
		for (Iterator<Prototype> iterProto = prototypes.iterator(); iterProto.hasNext();) {
			Prototype proto = iterProto.next();
			HelmaPrototypeTreeObject internalProto = new HelmaPrototypeTreeObject(proto, this);
			String protoName = proto.getName();
			intermediateResult.put(protoName, internalProto);
		}
		ArrayList<HelmaPrototypeTreeObject> result = new ArrayList<HelmaPrototypeTreeObject>();
		
		// Loop over Prototypes set parentPrototype and generate result
		for (Iterator<Prototype> iterProto = prototypes.iterator(); iterProto.hasNext();) {
			Prototype proto = iterProto.next();
			if (proto.getParentPrototype() != null) {
				Prototype parentProto = proto.getParentPrototype();
				intermediateResult.get(proto.getName()).setBasePrototype(intermediateResult.get(parentProto.getName()));
			}
			result.add(intermediateResult.get(proto.getName()));
		}
		return (ITreeObject[]) result.toArray(new ITreeObject[result.size()]);
	}

	public boolean hasChildren() {
		return app.typemgr.getPrototypes().size() > 0;
	}

	public Object getAdapter(Class key) {
		return null;
	}

	public String getName() {
		return app.toString();
	}

	public String getRawName() {
		return getName();
	}

	public ITreeParent getParent() {
		return null;
	}

	public String toString() {
		return getName();
	}

	public ResourceContainer getResource() {
		return null;
	}

	public int compare(ITreeObject element, Comparator comparator) {
		return comparator.compare(this.getName(), element.getName());
	}
}
